<?php

namespace api\finance\controller;

use think\facade\Request;
use WeChatPay\Crypto\Rsa;
use WeChatPay\Crypto\AesGcm;
use WeChatPay\Formatter;
use \aaa\Model;

class MoneyChargeNotifyController extends \Aaa\Controller {

    //支付宝
    public function alipay() {
        $params = $this->param();
        $params = array_map('htmlspecialchars_decode', $params);
        require_once CMF_ROOT . 'vendor/alipay-sdk-PHP-4.9.2/aop/AopCertClient.php';
        $aop = new \AopCertClient();
        $rsaPublicKeyFilePath = CMF_ROOT . '/data/config/alipay/alipayCertPublicKey.crt';
        $aop->alipayrsaPublicKey = $aop->getPublicKey($rsaPublicKeyFilePath);
        $result = $aop->rsaCheckV1($params, null, 'RSA2');//验签通过
        if ($result) {
            if ($params['trade_status'] == 'TRADE_SUCCESS') {
                $this->add($params['out_trade_no'], '支付宝', 3);
            }
            exit('success');
        } else {
            exit('fail');
        }
    }

    //微信
    public function wechatpay() {
        $config = cmf_get_option('system/api/wechat');
        $inWechatpaySignature = Request::header('Wechatpay-Signature');// 请根据实际情况获取
        $inWechatpayTimestamp = Request::header('Wechatpay-Timestamp');// 请根据实际情况获取
        $inWechatpaySerial = Request::header('Wechatpay-Serial');// 请根据实际情况获取
        $inWechatpayNonce = Request::header('Wechatpay-Nonce');// 请根据实际情况获取
        $inBody = file_get_contents('php://input');;// 请根据实际情况获取，例如: file_get_contents('php://input');
        $apiv3Key = $config['apiKey'];// 在商户平台上设置的APIv3密钥

        // 根据通知的平台证书序列号，查询本地平台证书文件，
        $platformPublicKeyInstance = Rsa::from('file://' . CMF_ROOT . $config['cert'], Rsa::KEY_TYPE_PUBLIC);

        // 检查通知时间偏移量，允许5分钟之内的偏移
        $timeOffsetStatus = 30 >= abs(Formatter::timestamp() - (int)$inWechatpayTimestamp);
        $verifiedStatus = Rsa::verify(// 构造验签名串
            Formatter::joinedByLineFeed($inWechatpayTimestamp, $inWechatpayNonce, $inBody), $inWechatpaySignature, $platformPublicKeyInstance);
        if ($timeOffsetStatus && $verifiedStatus) {
            // 转换通知的JSON文本消息为PHP Array数组
            $inBodyArray = (array)json_decode($inBody, true);
            $ciphertext = $inBodyArray['resource']['ciphertext'];
            $nonce = $inBodyArray['resource']['nonce'];
            $aad = $inBodyArray['resource']['associated_data'];
            // 加密文本消息解密
            $inBodyResource = AesGcm::decrypt($ciphertext, $apiv3Key, $nonce, $aad);
            // 把解密后的文本转换为PHP Array数组
            $inBodyResourceArray = (array)json_decode($inBodyResource, true);
            if ($inBodyResourceArray['trade_state'] == 'SUCCESS') {
                $this->add($inBodyResourceArray['out_trade_no'], '微信', 3);
            }
            exit('success');
        }
        exit('error');
    }

    //魔宝支付宝
    public function mobaopayAlipay() {
        file_put_contents('22.txt', print_r($this->param, true));
        $data = $this->param();
        $testData = [
            'tradeAmt' => '0.01',
            'merchUrl' => 'https://api.pnsss.com/api/finance/MoneyChargeNotify/mobaopay',
            'tradeTime' => '20220726152049',
            'custNo' => '199950003160',
            'orderNo' => '1173202207266124666',
            'notifyTime' => '20220726152101',
            'orderStatus' => '00',
            'merchTradeNo' => '167103',
            'signMsg' => 'jXKGjKISqgs+bvtSzyOs6FJ456FaC5StwGR3LwZ7iAMBMPPwDDAJ7mKtmsdwTHbLOiKkOf9cNYgvOl0rsWWLCDY4o0oddtafptmbVh+sd9diI4lU3BkwafPKpm0ZU/Bu1b8IoRRF70D1TsScfiCfu1hjinK4midJfwxesCHqjkDmdjoEm4Fth/LzNDlW3V2Qr9OaR9HPyxDJwJC1kQ88M183FqCimI5gvtIVIGB2BQ5kec1XjACyyy/0U9/F46tPtzWiUPoiSJwcPUr5zhM/vuN8qvY/94xjpBWZM/elbA/Tqitregw2lvdpnByKDdazm5KiA8dk4nu+WbBL8TuwcQ==',
        ];
        //$data = $testData;
        if ($this->mobaopayVerifySign($data)) {
            $this->add($data['merchTradeNo'], '支付宝', 3);
            echo '{"returnCode" :"1" , "returnMsg" : "SUCCESS"}';
        } else {
            echo '{"returnCode" : "0" , "returnMsg" : "FAIL"}';
        }
        exit;
    }
    //魔宝微信
    public function mobaopayWxpay() {
        $data = $this->param();
        if ($this->mobaopayVerifySign($data)) {
            $this->add($data['merchTradeNo'], '微信', 3);
            echo '{"returnCode" :"1" , "returnMsg" : "SUCCESS"}';
        } else {
            echo '{"returnCode" : "0" , "returnMsg" : "FAIL"}';
        }
        exit;
    }
    //魔宝验签
    private function mobaopayVerifySign($data) {
        $config = cmf_get_option('system/api/mobaopay');
        $signMsg = base64_decode($data['signMsg']);
        unset($data['signMsg']);
        ksort($data);
        $str = [];
        foreach ($data as $k => $v) {
            $str[] = "$k=$v";
        }
        $str = implode('&', $str);
        $pk = file_get_contents(CMF_ROOT . $config['mobaopayCert']);
        $pk = openssl_pkey_get_public($pk);
        if ($pk) {
            if (openssl_verify($str, $signMsg, $pk, OPENSSL_ALGO_MD5)) {
                return true;
            } else {//签名错误
                return false;
            }
        } else {//Mo宝公钥证书
            return false;
        }
    }

    //更新充值记录
    private function add($id, $bank, $status) {
        $where = [
            'id' => $id,
            'bank' => "{$bank}充值",
            'status' => 0
        ];
        $item = db('finance_money_charge')->where($where)->find();
        $time = time();
        if ($item) {
            if ($status == 3) {
                $model = new Model;
                $model->moneyInc($item['amount_received'], '在线充值', "{$bank}充值，充值编号：${$item['id']}", $item['user_id'], $bank);
            }
            $data = [
                'id' => $id,
                'receive_time' => $time,
                'status' => $status,
                'editor' => $bank
            ];
            db('finance_money_charge')->update($data);
        }
    }

    public function payReturn() {
        echo '充值成功，请返回平台继续操作<script>history.back();</script>';
        exit;
    }

    public function payReturnWap() {
        $h5Url = cmf_get_option('system/site')['h5Url'];
        header("Location: {$h5Url}static/html/chargeAlipay.html");
        exit;
    }


}